<template>
    <!-- <el-row :gutter="10" style="align-items: center;justify-content: space-between;margin-bottom: 50px;width: 100%;">
        <el-col :span="5">
            <el-row style="align-items: center;">
                <el-col :span="8">
                    <el-text style="font-size: 18px;">用户名：</el-text>
                </el-col>
                <el-col :span="16">
                    <el-input v-model="searchName" clearable placeholder="请输入关键字"></el-input>
                </el-col>
            </el-row>
        </el-col>
        <el-col :span="6">
            <el-row style="align-items: center;">
                <el-col :span="9">
                    <el-text style="font-size: 18px;">账号类型：</el-text>
                </el-col>
                <el-col :span="15">
                    <el-select v-model="searchIsAdmin" class="m-2" placeholder="Select" size="large">
                        <el-option value="管理员">管理员</el-option>
                        <el-option value="普通用户">普通用户</el-option>
                    </el-select>
                </el-col>
            </el-row>
        </el-col>
        <el-col :span="7">
            <el-row style="align-items: center;">
                <el-col :span="9">
                    <el-text style="font-size: 18px;">注册时间区间：</el-text>
                </el-col>
                <el-col :span="15">
                    <el-date-picker v-model="value2" type="datetimerange" start-placeholder="区间最小值" end-placeholder="区间最大值"
                        format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                </el-col>
            </el-row>
        </el-col>
        <el-col :span="6" style="display: flex;justify-content: right">
            <el-button type="primary" style="width: 30%;height: 100%;" @click="searchUsers">筛选</el-button>
        </el-col>
    </el-row> -->

    <el-text type="primary" size="large">
        <h1 class="my-h1">用户管理</h1>
    </el-text>


    <el-table :data="usersData" style="width: 100%">
        <el-table-column fixed prop="uid" label="用户ID" width="100" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号码" width="130" />
        <el-table-column label="账号类型" width="130">
            <template #default="scope">
                <el-tag v-if="scope.row.isAdmin" type="success">管理员账号</el-tag>
                <el-tag v-else>普通用户账号</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="210" />
        <el-table-column prop="updateTime" label="最后一次更新时间" width="220" />
        <el-table-column fixed="right" label="操作" width="150">
            <template #default="scope">
                <el-button plain type="primary" size="small" @click="updateUser(scope.row)">修改</el-button>
                <el-button plain type="danger" size="small" :disabled="scope.row.isAdmin"
                    @click="deleteUser(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-row style="margin-top: 20px;justify-content: space-between;">

            <el-button type="primary" style="width: 100px;height: 40px;" @click="isInsert = true">添加用户</el-button>
    </el-row>







    <el-dialog v-model="isUpdate" title="修改用户" width="40%" style="border-radius: 10px;">
        <el-form label-position="left" label-width="150px" :model="userUpdateFrom" style="max-width: 460px;margin: 0 auto;" :rules="fromRules">
            <div style="font-size: 12px;color: gray;margin-bottom:30px;text-align: center;">*部分数据不予手动修改，将不进行展示*</div>
            <el-form-item label="用户ID（唯一键）">
                <el-input v-model="userUpdateFrom.uid" disabled />
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userUpdateFrom.username" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="userUpdateFrom.email" />
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
                <el-input v-model="userUpdateFrom.phone" />
            </el-form-item>
            <el-form-item label="账号类型">
                <el-col>
                    <div style="font-size: 12px;color: gray;">*账号类型影响到权限等级，请慎重*</div>
                </el-col>
                <el-col>
                    <el-radio-group v-model="userUpdateFrom.isAdmin" size="large">
                        <el-radio-button label="false" @click="updateIsAdmin(false)">普通用户</el-radio-button>
                        <el-radio-button label="true" @click="updateIsAdmin(true)">管理员</el-radio-button>
                    </el-radio-group>
                </el-col>

            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="isUpdate = false">关闭</el-button>
            <el-button type="primary" @click="submit_updateUser">提交</el-button>
        </template>
    </el-dialog>

    <el-dialog v-model="isInsert" title="添加用户" width="40%" style="border-radius: 10px;">
        <el-form label-position="left" label-width="150px" :model="userInsertFrom" style="max-width: 460px;margin: 0 auto;" :rules="fromRules">
            <div style="font-size: 12px;color: gray;margin-bottom:30px;text-align: center;">*部分数据无需手动添加，将不进行展示*</div>
            <el-form-item label="用户ID（唯一键）">
                <el-input v-model="userInsertFrom.uid" disabled />
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userInsertFrom.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="userInsertFrom.password" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInsertFrom.email" />
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
                <el-input v-model="userInsertFrom.phone" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="isInsert = false">关闭</el-button>
            <el-button type="primary" @click="submit_insertUser">提交</el-button>
        </template>
    </el-dialog>
</template>

<script>
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MD5 } from 'crypto-js';

axios.defaults.baseURL = '/api'

export default {
    data() {
        return {
            usersData: [],
            isUpdate: false,
            userUpdateFrom: {},
            isInsert: false,
            userInsertFrom: {
                uid: '添加后自动生成',
                username: '',
                password: '123456',
                email: '',
                phone: '',
                isAdmin: false,
            },
            fromRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符之间', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { pattern: /^1\d{10}$/, message: '请输入正确的电话号码', trigger: 'blur' }
                ],
            },
            // searchName: '',
            // searchIsAdmin: '普通用户',
        }
    },
    created() {
        this.getUsersData()
    },
    methods: {
        getUsersData() {
            axios.get('/users')
                .then(result => {
                    if (result.data.code === 1) {
                        this.usersData = result.data.data;
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        },
        searchUsers() {
            ElMessage.info("筛选条件中")
        },
        deleteUser(user) {
            if (user.isAdmin) {
                ElMessage.warning("管理员账号不能被删除！！！");
                return;
            }
            let arr = [];
            arr.push(user.uid);
            axios.delete('/users/' + arr)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("删除成功");
                        this.getUsersData();
                    } else {
                        ElMessage.error("删除失败")
                        console.log(result.data);
                    }
                })
                .catch(err => {
                    console.log(err);
                    if (err.response.status === 500) {
                        ElMessage.info("后端服务器出现异常");
                        return;
                    }
                    ElMessage.error("删除失败！！！");
                })
        },
        updateUser(user) {
            if (user.isAdmin) {
                if (user.uid !== this.$store.state.user.uid) {
                    ElMessage.warning("不能修改其他管理员的信息！！！");
                    return;
                }
            }
            this.userUpdateFrom = JSON.parse(JSON.stringify(user));
            this.isUpdate = true;
        },
        submit_updateUser() {
            const data = {
                uid: this.userUpdateFrom.uid,
                username: this.userUpdateFrom.username,
                email: this.userUpdateFrom.email,
                phone: this.userUpdateFrom.phone,
                isAdmin: this.userUpdateFrom.isAdmin,
            }
            axios.put('/users', data)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("修改成功");
                        this.getUsersData();
                        this.isUpdate = false;
                    } else {
                        if (result.data.msg === "username_exist") {
                            ElMessage.info("用户名 " + this.userUpdateFrom.username + " 已被占用");
                            return;
                        }
                        ElMessage.info("添加失败");
                        console.log(result.data);
                    }
                })
                .catch(err => {
                    console.log(err);
                    if (err.response.status === 500) {
                        ElMessage.info("后端服务器出现异常");
                    }
                })
        },
        updateIsAdmin(to) {
            if (this.userUpdateFrom.isAdmin && !to) {
                ElMessage.warning("权限等级只允许上升不允许下降");
                setTimeout(() => this.userUpdateFrom.isAdmin = true, 200)
            } else if(!this.userUpdateFrom.isAdmin && to) {
                ElMessageBox.confirm(
                    '用户被赋予管理员权限，后将无法解除！！！',
                    '警告',
                    {
                        confirmButtonText: '继续操作',
                        cancelButtonText: '取消操作',
                        type: 'warning',
                    }
                )
                    .then(() => {
                        ElMessage({
                            type: 'info',
                            message: '表单提交后将生效',
                        })
                    })
                    .catch(() => {
                        setTimeout(() => this.userUpdateFrom.isAdmin = false, 200)
                    })
            }
        },
        submit_insertUser() {
            const data = {
                username: this.userInsertFrom.username,
                password: MD5(this.userInsertFrom.password).toString(),
                email: this.userInsertFrom.email,
                phone: this.userInsertFrom.phone,
            }
            axios.post('/users', data)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("添加成功");
                        this.getUsersData();
                        this.isInsert = false;
                    } else {
                        if (result.data.msg === "username_exist") {
                            ElMessage.info("用户名 " + this.userInsertFrom.username + " 已被占用");
                            return;
                        }
                        ElMessage.info("添加失败");
                        console.log(result.data);
                    }
                })
                .catch(err => {
                    console.log(err);
                    if (err.response.status === 500) {
                        ElMessage.info("后端服务器出现异常");
                    }
                })
        },

    }
}
</script>

<style scoped>
.my-h1 {
    color: #000;
    text-align: center;
    font-size: 28px;
    margin: 10px 0;
}
</style>